/**
 * 登录页面
 * @module views
 * @export {Login}
*/

import React, { useState, useEffect } from 'react'
import { Card, Input, Button, Spin, message } from 'antd'
import { useNavigate } from 'react-router-dom'
import { UserOutlined, KeyOutlined } from '@ant-design/icons'
import { servicePath } from '@src/api/axios'
import axios from 'axios'
import 'antd/dist/antd.css'
import style from './index.module.css'

export const Login = () => {
  //用户名
  const [username, setUsername] = useState('')
  // 密码
  const [password, setPassword] = useState('')
  // 加载状态
  const [loading, setLoading] = useState(true)
  const navigate = useNavigate()

  const loginClick = () => {

    if (!username) {
      message.error('用户名不能为空')
      return false
    } else if (!password) {
      message.error('密码不能为空')
      return false
    }

    let dataProps = {
      'username': username,
      'password': password,
      'openId': localStorage.getItem('openId')
    }

    // 向中台发送post请求
    console.log('/' + servicePath.checkLogin, '++++++++')
    axios({
      method: 'post',
      url: `/${servicePath.checkLogin}`,
      // url: ' http://127.0.0.1:7001/admin/checkLogin',
      data: dataProps, // 
      withCredentials: true // 是否携带凭证
    })
      .then(
        res => {
          setLoading(false)
          // console.log(res, '----------')
          if (res.data.code == 200) {
            localStorage.setItem('openId', res.data.openId)
            setLoading(true)
            setTimeout(() => {
              setLoading(false)
              navigate('/')
            }, 400)

          } else {
            message.error('用户名密码错误')
          }
        }
      )
  }

  useEffect(() => {
    setTimeout(() => {
      setLoading(false)
    }, 500)
  }, [])

  // useEffect(() => {
  //   console.log(username, '+++++++++')
  // }, [username])

  return (
    <div className={style.login_div}>
      <Spin spinning={loading}>
        <Card
          className={style.card_login}
          title="用户登录"
          bordered={true}
          loading={false}
        >
          <Input
            id="username"
            size="large"
            placeholder="请输入账号"
            onChange={e => setUsername(e.target.value)}
            prefix={<UserOutlined />}
          />
          <br />
          <br />
          <Input.Password
            id="password"
            placeholder="请输入密码"
            size="large"
            onChange={e => setPassword(e.target.value)}
            prefix={<KeyOutlined />}
          />
          <br />
          <br />
          <Button
            className={style.login_btn}
            type="primary"
            size="middle"
            onClick={loginClick}
          >登录</Button>
        </Card>
      </Spin>
    </div>
  )
}